import {getJson, postJson} from '../utils/request'
import {apiConfig} from '../constants/api'
import Taro from '@tarojs/taro'

export function getTopicList (params) {
  return async dispatch => {
    let res = await getJson(apiConfig.topics, params)
    console.log(res);
    if(res && res.data) {
      if(res.data.success) {
        dispatch({type : 'getTopicList', list: res.data.data})
      }
    }
  }
}

export function getNextTopicList (params) {
  return async dispatch => {
    let res = await getJson(apiConfig.topics, params)
    console.log(res);
    if(res && res.data) {
      if(res.data.success && res.data.data.length) {
        dispatch({type : 'appendTopicList', list: res.data.data, page: params.page })
      }
    }
  }
}

export function getTopicInfo (params) {
  return async dispatch => {
    let res = await getJson(apiConfig.topicsInfo + params.id, params)
    if(res && res.data && res.data.success) {
      dispatch({type: 'getTopicInfo', infoData: res.data.data})
    }else{
      console.log('请求话题详情失败');
      
    }
  }
}

// 点赞

export function admireTopic (params) {
  return async dispatch => {
    let res = await postJson(apiConfig.upreply+params.id+'/ups', params)
    if(res && res.data && res.data.success) {
      dispatch({type: 'admireSuccess'})
    }else{
      Taro.showToast({title:'点赞失败', icon: 'none'})
    }
  }
}

export async function sendReply (params){
  let res = await postJson(apiConfig.replytopic + params.topicid + '/replies', params)
  if(res && res.data && res.data.success) {
    return  res.data
  }else{
    Taro.showToast({title:'评论失败', icon: 'none'})
  }
  return false
}

export async function createTopic(params) {
  let res = await postJson(apiConfig.publishTopic, params)
  if(res && res.data && res.data.success) {
    return res.data
  }else{
    Taro.showToast({title:'发布失败', icon: 'none'})
  }
  return false
}
export async function updateTopic(params) {
  let res = await postJson(apiConfig.updatetopic, params)
  if(res && res.data && res.data.success) {
    return res.data
  }else{
    Taro.showToast({title:'更新失败', icon: 'none'})
  }
  return false
}